/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lu.manage.core.common.page;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.lu.manage.core.common.constant.SystemConstant;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.model.Dept;
import com.lu.manage.modular.system.service.DeptService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Table默认的分页参数创建
 */
public class LayuiPageFactory {

    /**
     * 获取layui table的分页参数
     *
     * @author fengshuonan
     * @Date 2019/1/25 22:13
     */
    public static Page defaultPage(Map<String, Object> map) {

        //第几页
        int page = Integer.valueOf((String)map.get(SystemConstant.PAGE));

        //每页多少条数据
        int limit = Integer.valueOf((String)map.get(SystemConstant.LIMIT));

        //移除参数
        map.remove(SystemConstant.PAGE);
        map.remove(SystemConstant.LIMIT);

        return new Page(page, limit);
    }

    /**
     * 根据机构 - 数据范围
     * @param map
     * @return
     */
    public static QueryWrapper deptScope(DeptService deptService, Map<String, Object> map){

        QueryWrapper queryWrapper = new QueryWrapper();

        List<String> deptIds = new ArrayList<>();

        String deptId = (String) map.get(SystemConstant.DEPT_ID);

        map.remove(SystemConstant.DEPT_ID);

        //删除当前部门下的所有子部门
        List<Dept> deptList = deptService.getDeptsLikePids(deptId);

        deptIds  = deptList.stream().map(o -> o.getId()).collect(Collectors.toList());

        deptIds.add(deptId);
        queryWrapper.in(SystemConstant.DEPT_ID, deptIds);

        return queryWrapper;
    }

    /**
     * 创建layui能识别的分页响应参数
     *
     * @author fengshuonan
     * @Date 2019/1/25 22:14
     */
    public static SuccessTip listPage(IPage page) {
        SuccessTip successTip = new SuccessTip();
        successTip.setCount(page.getTotal());
        successTip.setData(page.getRecords());
        return successTip;
    }
}
